/**
 * https://leetcode.cn/problems/find-k-closest-elements/
 * 658.找到K个最接近的元素
 * medium, 叶佳豪 2024.9.1
 * 滑动窗口
 */

class Solution {
public:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        int l=0,r=0;
        int start,end,minsub=INT_MAX,sum=0;

        while(r<arr.size()){
            sum+=abs(arr[r]-x);
            if(r-l+1==k){
                if(sum<minsub){
                    start=l;
                    end=r;
                    minsub=sum;
                }
                sum-=abs(arr[l++]-x);
            }
            r++;
        }

        return vector<int>(arr.begin()+start,arr.begin()+end+1);
    }
};